package com.fzf.org.toolkit;

import com.fzf.org.dao.entities.BasicDO;
import com.fzf.org.exception.BizException;
import com.fzf.org.exception.BizExceptionTypeEnum;

public class BasicContext {
    private static final ThreadLocal<BasicRecord> userThreadLocal = new ThreadLocal<>();

    public static void setBasicInfoToThreadLocal(String token){
        BasicDO basic = JWTAuthenticator.getBasicFromToken(token);
        BasicRecord userRecord = new BasicRecord(
                basic.getId(),
                basic.getAccount(),
                basic.getRoleId(),
                token
        );
        userThreadLocal.set(userRecord);
    }

    public static void remove(){
        checkBasicStatus();
        userThreadLocal.remove();
    }

    public static Long getBasicId(){
        checkBasicStatus();
        return userThreadLocal.get().id();
    }

    public static String getBasicAccount(){
        checkBasicStatus();
        return userThreadLocal.get().account();
    }

    public static Long getBasicRoleId(){
        checkBasicStatus();
        return userThreadLocal.get().roleId();
    }

    public static String getAuthorizationToken(){
        checkBasicStatus();
        return userThreadLocal.get().token();
    }

    private static void checkBasicStatus(){
        if (userThreadLocal.get() == null) throw new BizException(BizExceptionTypeEnum.USER_STATUS_ERROR);
    }

    private record BasicRecord(Long id, String account, Long roleId, String token) {

    }
}
